import json
import threading
import time

from django.shortcuts import render
from django.shortcuts import HttpResponse
import requests
from DataFactory.common import create_sell_order

# Create your views here.


def create_order_data(request, order_type):

    return render(request,
                  './createData.html',
                  {'orderType': order_type}
                  )


class OrdersThread (threading.Thread):
    def __init__(self, func, source_type, host, customer_type, payment_method, order_type, quotation_type, order_status, quotation_status, token_needed):
        threading.Thread.__init__(self)
        self.result = self.func(self.host, self.customer_type, self.payment_method, self.quotation_type, self.quotation_status, self.token_needed)
        self.func = func
        self.source_type = source_type
        self.host = host
        self.customer_type = customer_type
        self.payment_method = payment_method
        self.order_type = order_type
        self.quotation_type = quotation_type
        self.order_status = order_status
        self.quotation_status = quotation_status
        self.token_needed = token_needed

    def run(self):
        if self.source_type == "sellorder" or self.source_type == "SellOrder" or self.source_type == "Sellorder":
            self.result = self.func(self.host, self.customer_type, self.payment_method, self.order_type, self.order_status, self.token_needed)
        elif self.source_type == 'quotation' or self.source_type == 'Quotation':
            pass

    def get_result(self):
        try:
            return self.result
        except Exception as e:
            print(e)
            return None


def create_order(request):
    global host_url, customer_id, orders, thread
    if request.method == 'POST':  # 当提交表单时
        # 判断是否传参
        if request.POST:
            source_type = request.POST.get('sourceType', 0)
            host = request.POST.get('environment', 0)
            customer_type = request.POST.get('customerType', 0)
            payment_method = request.POST.get('paymentMethod', 0)
            order_count = request.POST.get('orderCount', 0)

            if host == "Test":
                host_url = "http://erp.test.jimuitech.com"
            elif host == "UAT":
                host_url = "http://erp.uat.jimuitech.com"
            elif host == "Stable":
                host_url = "http://erp.stable.jimuitech.com"

            session = requests.session()
            login_data = {
                "username": "kap1chn",
                "password": "A1VWQFLPC8EWsmxFkMR8tw==",
                "loginSource": "ERP"
            }
            login_result = session.post(url=host_url + "/platform/admin/auth/login",
                                        data=json.dumps(login_data),
                                        headers={
                                             "Content-Type": "application/json"
                                         }
                                        ).content
            token_needed = json.loads(login_result)["data"]["token"]

            order_final = []
            threads = []
            for i in range(1, int(order_count) + 1):
                if source_type == 'sellorder' or source_type == 'SellOrder' or source_type == 'sellOrder' or source_type == 'Sellorder':
                    order_type = request.POST.get("orderType", 0)
                    order_status = request.POST.get("orderStatus", 0)
                    thread = OrdersThread(func=create_sell_order.create_order, source_type=source_type, host=host_url, customer_type=customer_type, payment_method=payment_method, order_type=order_type, order_status=order_status, token_needed=token_needed)
                elif source_type == 'quotation' or source_type == 'Quotation':
                    quotation_type = request.POST.get("quotationShopType", 0)
                    quotation_status = request.POST.get("quotationStatus", 0)
                    thread = OrdersThread(func=create_sell_order.create_quotation, source_type=source_type, host=host_url, customer_type=customer_type, payment_method=payment_method, order_type=None, quotation_type=quotation_type, order_status=None, quotation_status=quotation_status, token_needed=token_needed)
                thread.start()
                threads.append(thread)
                time.sleep(0.3)
            for t in threads:
                t.join()
                order_final.append(t.get_result())
            return HttpResponse(json.dumps(order_final, ensure_ascii=False), content_type="application/json,charset=utf-8")
        else:
            return HttpResponse('输入为空')

    else:
        return HttpResponse('方法错误')
